// Global var
var last_pub_timestamp = 0;
var posted_map = {};

function SendEmail (key, to, title, content) {
 //alert (to + " " + title + "  " + content);
 $.ajax({
  type: "POST",
  url: "https://mandrillapp.com/api/1.0/messages/send.json",
  data: {
    'key'     : key,
    'message' : {
      'from_email': 'vishnukanwar@gmail.com',
      'to'        : [
                     {
                      'email': to,
                      'name' : 'NEWS',
                      'type' : 'to'
                     }
                    ],
      'autotext'  : 'true',
      'subject'   : title,
      'html'      : content
    }
  }
 }).done(function(response) {
   $( "#email_response" ).text ( $(response).text() );
 });
}



function ReadRSS (rssurl, tag, email, key) {
  $.get(rssurl, function(data) {
    $(data). find ("item"). each ( function () {
      var pubDate = $(this). find ( "pubDate" ). text ();
      var title   = $(this). find ( "title" ). text ();
      //alert(title);

      var date = new Date(pubDate);
      var timestamp = Math.round ( date.getTime()/1000 );
      //if ( timestamp <= last_pub_timestamp ) {
      if (title in posted_map) {
          $( "#already_posted_count" ).text ( 1 + parseInt($( "#already_posted_count" ).text (), 10) );
      } else {
        last_pub_timestamp = timestamp;
        posted_map[title] = '1';

        //$("#test").prepend ( pubDate + "<li>" + title + "</li><br>" );

        $.get( $(this). find ( "link" ).text(), function( data ) {
          var content = $(data). find(tag). html();
          if ( typeof content === "undefined") {
              $( "#content_not_found" ).text ( 1 + parseInt($( "#content_not_found" ).text (), 10) )
          } else {
            SendEmail (key, email, title, content);
            //alert ( content  );
            $( "#test" ).prepend( "<hr>" + email + "<br>" + title + "<br>" + pubDate + "<br>" + content  );
            $( "#new_post_count" ).text ( 1 + parseInt($( "#new_post_count" ).text (), 10) );
          }
        });
      }
    });
  });
}

